package com.whisperly.echotalk.starryb.utils;

import android.content.Context;
import android.view.View;

import com.google.android.material.snackbar.Snackbar;
import com.whisperly.echotalk.starryb.R;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailUtil {
    private static final String myEmailAccount = "1905333495@qq.com";
    private static String verificationCode = "";
    private static final String SYMBOLS = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";

    private static long verificationCodeTime = 0;

    private static String emailContent;
    private static String emailSubject;

    public static void showSnackBar(String type, View view, String content, Context context) {
        if (type.contentEquals("blue")) {
            Snackbar snackbar = Snackbar.make(view, content, Snackbar.LENGTH_SHORT);
            snackbar.getView().setBackgroundColor(context.getResources().getColor(R.color.colorBlue));
            snackbar.show();
        } else if (type.contentEquals("red")) {
            Snackbar snackbar = Snackbar.make(view, content, Snackbar.LENGTH_SHORT);
            snackbar.getView().setBackgroundColor(context.getResources().getColor(R.color.colorRed));
            snackbar.show();
        } else if (type.contentEquals("yellow")) {
            Snackbar snackbar = Snackbar.make(view, content, Snackbar.LENGTH_SHORT);
            snackbar.getView().setBackgroundColor(context.getResources().getColor(R.color.colorGold));
            snackbar.show();
        }
    }

    public static void generateCode() {
        Random random = new Random();
        char[] nonceChars = new char[5];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(random.nextInt(SYMBOLS.length()));
        }
        verificationCode = new String(nonceChars);
        verificationCodeTime = System.currentTimeMillis();
    }

    public static boolean isCodeValid() {

        long fiveMinutesInMillis = 5 * 60 * 1000;

        return (System.currentTimeMillis() - verificationCodeTime) <= fiveMinutesInMillis;
    }


    public static void sendEmail(String email, View view, Context context) {
        Locale currentLocale = Locale.getDefault();
        String currentLang = currentLocale.getLanguage();
        String time = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault()).format(new Date());
        switch (currentLang) {
            case "zh":
            default:
                emailSubject = "验证您的账号";
                emailContent ="<h3>\n" +
                        "\t<span style=\"font-size:16px;\">亲爱的用户：</span> \n" +
                        "</h3>\n" +
                        "<p>\n" +
                        "\t<span style=\"font-size:14px;\">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style=\"font-size:14px;\">&nbsp; <span style=\"font-size:16px;\">&nbsp;&nbsp;您好！您正在进行邮箱验证，本次请求的验证码为：<span style=\"font-size:24px;color:#FFE500;\"> "+verificationCode+"</span>,本验证码5分钟内有效，请在5分钟内完成验证。（请勿泄露此验证码）如非本人操作，请忽略该邮件。(这是一封自动发送的邮件，请不要直接回复）</span></span>\n" +
                        "</p>\n" +
                        "<p style=\"text-align:right;\">\n" +
                        "\t<span style=\"background-color:#FFFFFF;font-size:16px;color:#000000;\"><span style=\"color:#000000;font-size:16px;background-color:#FFFFFF;\"><span class=\"token string\" style=\"font-family:&quot;font-size:16px;color:#000000;line-height:normal !important;background-color:#FFFFFF;\">Blink Chat</span></span></span> \n" +
                        "</p>\n" +
                        "<p style=\"text-align:right;\">\n" +
                        "\t<span style=\"background-color:#FFFFFF;font-size:14px;\"><span style=\"color:#FF9900;font-size:18px;\"><span class=\"token string\" style=\"font-family:&quot;font-size:16px;color:#000000;line-height:normal !important;\"><span style=\"font-size:16px;color:#000000;background-color:#FFFFFF;\">"+time+"</span><span style=\"font-size:18px;color:#000000;background-color:#FFFFFF;\"></span></span></span></span> \n" +
                        "</p>";
                break;
            case "en":
                emailSubject = "Verify Your Account";
                emailContent = "<h3>\n" +
                        "\t<span style=\"font-size:16px;\">Dear user</span> \n" +
                        "</h3>\n" +
                        "<p>\n" +
                        "\t<span style=\"font-size:14px;\">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style=\"font-size:14px;\">&nbsp; <span style=\"font-size:16px;\">&nbsp;&nbsp;Hello! You are conducting email verification, and the verification code for this request is:<span style=\"font-size:24px;color:#FFE500;\"> "+verificationCode+"</span>This verification code is valid within 5 minutes. Please complete the verification within 5 minutes. (Please do not disclose this verification code) If it was not done by myself, please ignore this email. (This is an automatically sent email, please do not reply directly)</span></span>\n" +
                        "</p>\n" +
                        "<p style=\"text-align:right;\">\n" +
                        "\t<span style=\"background-color:#FFFFFF;font-size:16px;color:#000000;\"><span style=\"color:#000000;font-size:16px;background-color:#FFFFFF;\"><span class=\"token string\" style=\"font-family:&quot;font-size:16px;color:#000000;line-height:normal !important;background-color:#FFFFFF;\">Blink Chat</span></span></span> \n" +
                        "</p>\n" +
                        "<p style=\"text-align:right;\">\n" +
                        "\t<span style=\"background-color:#FFFFFF;font-size:14px;\"><span style=\"color:#FF9900;font-size:18px;\"><span class=\"token string\" style=\"font-family:&quot;font-size:16px;color:#000000;line-height:normal !important;\"><span style=\"font-size:16px;color:#000000;background-color:#FFFFFF;\">"+time+"</span><span style=\"font-size:18px;color:#000000;background-color:#FFFFFF;\"></span></span></span></span> \n" +
                        "</p>";
                break;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                Properties props = new Properties();
                props.put("mail.smtp.host", "smtp.qq.com");
                Session session = Session.getInstance(props, null);
                try {
                    MimeMessage msg = new MimeMessage(session);
                    msg.setFrom(new InternetAddress(myEmailAccount, "Blink Chat", "UTF-8"));
                    msg.setRecipients(Message.RecipientType.TO, email);
                    msg.setSubject(emailSubject);
                    msg.setSentDate(new Date());
                    msg.setContent(emailContent, "text/html;charset=UTF-8");
                    Transport.send(msg, myEmailAccount, "wilvdvxubhhofaca");
                    showSnackBar("blue", view, "The verification code has been sent to your email!", context);
                } catch (MessagingException | UnsupportedEncodingException e) {
                    SendGmail.gmailSender(email,view,context);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static String getVerificationCode() {
        return verificationCode;
    }

    public static void setVerificationCode(String verificationCode) {
        EmailUtil.verificationCode = verificationCode;
    }
}
